import requests
from lxml import etree
import os

if __name__ == '__main__':
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
    url = "http://pic.netbian.com/4kmeinv/"
    response = requests.get(url=url, headers=headers)
    # 手动设定响应数据的编码格式
    # response.encoding = "utf-8"
    page_text = response.text

    # 数据解析：src的属性
    tree = etree.HTML(page_text)
    li_list = tree.xpath("//div[@class='slist']/ul/li")
    print(li_list)
    #创建一个文件夹
    if not os.path.exists("./picLibs"):
        os.mkdir("./picLibs")
    for li in li_list:
        img_src = "http://pic.netbian.com" + li.xpath("./a/img/@src")[0]
        img_name = li.xpath("./a/img/@alt")[0] + ".jpg"
        # 通用处理中文冷的解决方案
        img_name = img_name.encode("iso-8859-1").decode("gbk")
        # print(img_name, img_src)
        # 持久化存储
        imgdata = requests.get(url=img_src, headers=headers).content
        imgpath = "picLibs/"+img_name
        with open(imgpath,"wb") as fp:
            fp.write(imgdata)
            print(img_name,"下载成功")